/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.frontend.server.data;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gwtportlets.portlet.smartgwt.client.DataTransferObject;
import org.gwtportlets.portlet.smartgwt.client.SmartPortletFactory;
import org.gwtportlets.portlet.smartgwt.server.DataProviderObject;
import za.org.foobar.famon.frontend.client.dto.EnumDto;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public abstract class EnumDpo implements DataProviderObject {
    private final Log log = LogFactory.getLog(getClass());

    protected Map<Integer, String> nameMap = new HashMap<Integer, String>();
    protected List<Integer> order = new ArrayList<Integer>();

    public void add(int id, String value) {
        order.add(id);
        nameMap.put(id, value);
    }

    public void add(Class cls) {
        add(cls, null);
    }

    public void add(Class cls, String prefix) {
        if (prefix == null) {
            prefix = "";
        }
        for (Field field : cls.getFields()) {
            String name = field.getName();
            if (Modifier.isPublic(field.getModifiers()) && name.startsWith(prefix)) {
                name = name.substring(prefix.length()).replace("_", " ").toLowerCase();
                try {
                    add(field.getInt(null), name);
                } catch (IllegalAccessException ignored) {
                }
            }
        }
    }

    public List<DataTransferObject> fetchData(SmartPortletFactory f) {
        log.info("Fetch Enum for " + getDataSourceId());
        List<DataTransferObject> list = new ArrayList<DataTransferObject>();
        for (int i : order) {
            list.add(new EnumDto(i, nameMap.get(i)));
        }
        log.info("Returning " + list.size());
        return list;
    }

    public DataTransferObject updateData(SmartPortletFactory f) {
        return null;
    }

    public DataTransferObject addData(SmartPortletFactory f) {
        return null;
    }

    public DataTransferObject removeData(SmartPortletFactory f) {
        return null;
    }
}
